function getTimeLeft(createTime) {
	let time1 = Date.parse(new Date()); //毫秒
	let time2 = createTime;
	let mss = time1 - time2;
	if (mss > 0) {
		if (mss > 86400000) {
			//大于24小时
			return util.getLocalDate1(time2)
			// debugger
		} else {
			if (mss > 3600000) {
				//大于1小时
				var hours = parseInt(mss / (60 * 60 * 1000))
				// debugger
				return hours + '小时前'
			} else {
				if (mss > 60000) {
					//大于1分钟
					var minutes = parseInt(mss % (60 * 60 * 1000) / 60000);
					return minutes + '分钟前'
				} else {
					var seconds = parseInt(mss % 60000);
					return seconds + '秒前'
				}
			}
		}
	}
}


const util = require('../../utils/util.js');
import api from '../../utils/request/api'
import {
	goodsDetail,
	getCommentList,
	addGoodsOfCart
} from '../../utils/request/apiurl'

Page({
	data: {
		commentList: [],
		// goodsList: [{
		// 	id: 1,
		// 	img: 'https://images.unsplash.com/photo-1551334787-21e6bd3ab135?w=640',
		// 	title: '1蒙牛  纯甄 常温酸牛奶 青柠抹茶牛油果口味200g*16礼盒装',
		// 	oldPrice: 68.00,
		// 	newPrice: 36.60,
		// 	sales: 32515
		// }, ],
		goodList: [],
		tasteNav: 0, //味道
		colorNav: 0, //颜色
		currentTasteId: '',
		currentColorId: '',
		shareWrap: true, //分享
		specificationsWrap: true, //规格
		goodNum: 1, //商品数量
		// goodPrice:0,//商品价格
		id: null,
		uid: '',
		rank: 0, //会员等级
		createTime: '', //评论时间
		searchGood: {
			page: 1,
			size: 20,
			pages: 0
		},
		isRequest: false,
		skuRepertory: 0, //sku库存
		currentNav: 0,
		skuId: '',
		sellCount: 0, //会员折扣
		artical:'',
		animationData:{},
		type:0,
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
    console.log("options",options)
    if (options.uid != undefined) {
      // console.log(1)
      var user = {}
      // var userInfo = wx.getStorageSync('userInfo');
      user['TJuid'] = options.uid //推荐人uid
      wx.setStorageSync('user', user);
    }
		// console.log(options)
		this.setData({
			type:options.type
		})
		var userInfo = wx.getStorageSync('userInfo');
		if (userInfo.rank) {
			this.setData({
				rank: userInfo.rank,
				id: options.goodId,
				uid: userInfo.uid,
				sellCount: userInfo.sellCount
			})
		}
		this.setData({
			id: options.goodId,
			// uid: userInfo.uid,
			// sellCount: userInfo.sellCount
		});
    if (options.shopid) {
      this.setData({
        id: options.shopid,
      })
      console.log("shopid", this.data.id)
    }
		// console.log(this.data.sellCount)
		this.getGoodList();
	},

  //动画集
  // fadeIn:function(){
  //   this.animation.translateY(0).step()
  //   this.setData({
  //     animationData: this.animation.export()//动画实例的export方法导出动画数据传递给组件的animation属性
  //   })    
  // },
  // fadeDown:function(){
  //   this.animation.translateY(300).step()
  //   this.setData({
  //     animationData: this.animation.export(),  
  //   })
  // }, 
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {

	},
	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {
		if (!this.data.isRequest && this.data.searchGood.page < this.data.searchGood.pages) {
			this.setData({
				searchGood: {
					page: this.data.searchGood.page + 1,
					size: 10,
					pages: this.data.searchGood.pages
				}
			})
			// console.log(this.data.searchGood)
			this.handleComment()
		}
	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {
		var that=this
		// console.log(that.data.uid)
	    return {
	      // title: '自定义转发标题',
	      path: 'pages/good-detail/good-detail?uid='+that.data.uid+'&goodId='+that.data.id+'&type=0',
	      success: function(res) {
			  // console.log(res)
	    //     var shareTickets = res.shareTickets;
	    //     if (shareTickets.length == 0) {
	    //         return false;
	    //     }
	    //     wx.getShareInfo({
	    //         shareTicket: shareTickets[0],
	    //         success: function(res){
					// // console.log(res)
	    //             var encryptedData = res.encryptedData;
	    //             var iv = res.iv;
	    //         }
	    //     })
	    //   },
	    //   fail: function(res) {
	    //     // 转发失败
	      }
	    }
	  },
	// 获取商品列表
	getGoodList() {
		var source = {
			id: this.data.id
		}
		api.post(goodsDetail.list, source).then(res => {
			// console.log(res)
			var goodList = this.data.goodList;
			// res.sku.forEach(v => {
			// 	v.curent = 0
			// })
			goodList.push(res);
			// goodList[0].shelfTime = goodList[0].shelfTime-goodList[0].createTime
			// console.log(goodList[0])
			goodList[0].createTime = util.getLocalDate(goodList[0].createTime)
			// goodList[0].shelfTime = util.getLocalDate1(goodList[0].shelfTime)
			goodList[0]['goodPrice'] = goodList[0].goodPrice;

			var url = []
			var obj = {}
			// console.log(goodList[0].url)
			if (goodList[0].url == null) {
				// console.log('111')
				obj = goodList[0].firstPicture
				url.push(obj)
				this.setData({
					'goodList[0].url': url
				})
			} else if (goodList[0].url.length == 0) {
				goodList[0].url.push(goodList[0].firstPicture)
			}
// 			else if(goodList[0].url.length>0){
// 				for (var i=0;i<goodList[0].url.length;i++){
// 					if(goodList[0].url[i]!=''&&goodList[0].url[i]!=null&&goodList[0].url[i]!=undefined){
// 						
// 					}
// 				}
// 			}
// 
			// this.setData({
			// 	goodList: goodList,
			// })
			// debugger
			// console.log(goodList[0].commonMember!=null)
			// if (this.data.rank == 1 && goodList[0].commonMember != null && goodList[0].commonMember != undefined && goodList[0].commonMember != '') {
			// 	goodList[0].goodPrice = goodList[0].commonMember;
			// 	this.setData({
			// 		goodList: goodList,
			// 	})
			// } else if (this.data.rank == 2 && goodList[0].middleMember != null && goodList[0].middleMember != undefined &&
			// 	goodList[0].middleMember != '') {
			// 	goodList[0].goodPrice = goodList[0].middleMember;
			// 	this.setData({
			// 		goodList: goodList,
			// 	})
			// } else if (this.data.rank == 3 && goodList[0].expertMember != null && goodList[0].expertMember != undefined &&
			// 	goodList[0].expertMember != '') {
			// 	goodList[0].goodPrice = goodList[0].expertMember;
			// 	this.setData({
			// 		goodList: goodList,
			// 	})
			// } else {
				// console.log(goodList[0].goodsDetails)
			// content.replace('<img', '<img style="max-width:100%;height:auto" ')	
			// const json = goodList[0].goodsDetails;
			// console.log(json)
			if(goodList[0].goodsDetails !== null){
			    this.data.artical = util.formatRichText(goodList[0].goodsDetails);
			}
			// console.log(this.data.artical)	

				this.setData({
					goodList: goodList,
					artical:this.data.artical
				})
			// }
			//规格数组
			// if(this.data.sellCount!=null){
			var skuList = []
			goodList[0].sku.forEach(v => {
				var dataList = v
				var goodsSku = JSON.parse(v.goodsSku)
				// console.log(goodsSku)
				dataList['skudata'] = ''
				for (var obj in goodsSku) {
					if (dataList['skudata'] == '') {
						dataList['skudata'] = goodsSku[obj]
					} else {
						dataList['skudata'] = dataList['skudata'] + '/' + goodsSku[obj]
					}

				}
				skuList.push(dataList)
			})
			this.setData({
				'goodList[0].skuList': skuList
			})
      console.log(this.data.goodList)
			// }else{
			// 	wx.switchTab({
			// 		url: '../personal-center/personal-center'
			// 	})
			// 	wx.showToast({
			// 		title: '请登录',
			// 		icon: 'none',
			// 		duration:2000,
			// 	})
			// }

			this.handleComment();
			if(this.data.type==1){
				this.setData({
					specificationsWrap: false
				})
			}
		}).catch(err => {
			console.log(err)
			wx.showToast({
				title: err.message,
				icon: 'none'
			})
		})
	},
	// 规格
	handleSKU() {
		this.setData({
			specificationsWrap: false
		})
		// var that=this;
		// that.setData({
		//   specificationsWrap: false
		// })
		// var animation = wx.createAnimation({
		//   duration: 600,//动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
		//   timingFunction: 'ease',//动画的效果 默认值是linear
		// })
		// this.animation = animation 
		// setTimeout(function(){
		//   that.fadeIn();//调用显示动画
		// },200)   
	},
	//确认加入购物车
	sureAddCar() {
		// console.log(this.data.currentNav, 'currentNavcurrentNav')
    //确认用户点击确认加入购物车缓存标识
    let shopObj = {
      shopId: this.data.id,
      shipIs:false,
    }
    //缓存判断用户是否需要重新加载商品列表页
    wx.setStorageSync('isLogin', true)
    wx.setStorageSync('shopObj', shopObj);
		if (wx.getStorageSync('userInfo') != '') {
			if (this.data.sellCount != null) {
				if (this.data.goodList[0].repertory == null || this.data.goodList[0].repertory == undefined || this.data.goodList[
						0].repertory == 0) {
					wx.showToast({
						title: '暂无库存',
						icon: 'none'
					})
					return false
				} else if (this.data.goodList[0].repertory != 0 && this.data.currentNav != 0) {
					if (this.data.goodList[0].skuList[this.data.currentNav].stock == 0) {
						wx.showToast({
							title: '暂无库存',
							icon: 'none'
						})
						return false
					}
					// for(var i=0;i<this.data.goodList[0].skuList.length ;i++){
					// 	if(this.data.goodList[0].skuList[i].stock==0){
					// 		wx.showToast({
					// 			title: '暂无库存',
					// 			icon: 'none'
					// 		})
					// 		return false
					// 	}
					// }
				}
				if (this.data.currentNav == 0) {
					if (this.data.goodList[0].skuList[0].stock == 0) {
						wx.showToast({
							title: '暂无库存',
							icon: 'none'
						})
						return false
					}
				}
				// debugger
				if (this.data.currentNav == 0) {
					// console.log(this.data.goodList[0].skuList[0].goodsPrice)
					// console.log(this.data.sellCount)
					var source = {
						uid: this.data.uid,
						goodsId: this.data.id,
						count: this.data.goodNum,
						sku: this.data.goodList[0].skuList[0].skuId,
            // goodsPrice: parseInt((this.data.goodList[0].skuList[0].goodsPrice) * (this.data.sellCount / 100)),
            goodsPrice: parseInt((this.data.goodList[0].skuList[0].goodsPrice)),
					}
				} else {
					var source = {
						uid: this.data.uid,
						goodsId: this.data.id,
						count: this.data.goodNum,
						sku: this.data.skuId,
						// goodsPrice: parseInt((this.data.goodList[0].skuList[this.data.currentNav].goodsPrice) * (this.data.sellCount /
            //   100)),
            goodsPrice: parseInt((this.data.goodList[0].skuList[this.data.currentNav].goodsPrice)),
					}
				}
				// debugger
				// console.log(source)
				api.post(addGoodsOfCart.list, source).then(res => {
					// console.log(res,4444444)
					if (res == 1) {
						var that=this
						wx.showToast({
						    title: '成功加入购物车',
						    icon: 'none',
						    success: function () {
							// that.setData({
							// 	specificationsWrap: true
							// })
                  setTimeout(function () {
                    wx.switchTab({
                      url: '../shopping-cart/shopping-cart'
                    })
						      }, 500);
						    }
						});

					}
				}).catch(err => {
					// console.log(err)
          wx.showToast({
            title: err.message,
            icon: 'none',
            success: function () {
              // setTimeout(function () {
              //   wx.navigateTo({
              //     url: '../good-special/good-special'
              //   })
              // }, 1000);
            }
          });
				})
			} else {
				wx.showToast({
					title: '请退出重新登录',
					icon: 'none',
					duration: 2000
				})
				return false
			}

		} else {
			// wx.showToast({
			// 	title: '暂未登录，请前去登录',
			// 	icon: 'none',
			// 	duration: 2000
			// })
			// wx.switchTab({
			// 	url: '../personal-center/personal-center'
			// })
			wx.showToast({
			    title: '暂未登录，请前去登录',
			    icon: 'none',
			    success: function () {
			      setTimeout(function() {
			        wx.switchTab({
			        	url: '../personal-center/personal-center'
			        })
			      }, 1000);
			    }
			});
		}



	},
	
	// changeTasteTab(event) {
	// 	console.log(event)
	// 	const currentIndex = event.currentTarget.dataset.index;
	// 	// this.data. currentTasteId = event.currentTarget.dataset.id;
	// 	// 给当前项增加class
	// 	if (this.data.tasteNav !== currentIndex) {
	// 		this.setData({
	// 			tasteNav: currentIndex
	// 		})
	// 	}
	// 	this.setData({
	// 		currentTasteId:event.currentTarget.dataset.type
	// 	})
	// 	// console.log(this.data.currentTasteId)
	// },
	// 选择分类
	changeColorTab(e) {
		// console.log(e)
		const event = e;
		// 给当前项增加class
		if(event.currentTarget.dataset.type.stock>0){
			this.changeColor(event)
		}
		
	},
	changeColor(event){
		// console.log(event,'eventevent')
		const currentIndex=event.currentTarget.dataset.index
		if (this.data.currentNav !== currentIndex) {
			this.setData({
				currentNav: currentIndex,
				skuRepertory: event.currentTarget.dataset.type.stock,
				skuId: event.currentTarget.dataset.type.skuId
			})
		}
		
		// this.data.currentColorId = event.currentTarget.dataset.id;
		// 给当前项增加class
		// if (this.data.goodList[0].sku[idx].curent !== currentIndex) {
		// 	this.data.goodList[0].sku[idx].curent = currentIndex
		// }
		// this.setData({
		// 	currentColorId: event.currentTarget.dataset.type
		// })
		this.setData({
			goodList: this.data.goodList,
		})
		// console.log(this.data.goodList[0])
	},
	// 减少
	reduceNum() {
		var goodNum = this.data.goodNum;
		if (goodNum > 1) {
			this.data.goodNum--;
		}
		this.setData({
			goodNum: this.data.goodNum
		})
	},
	// 增加
	addNum(e) {
		console.log(1)
		var goodNum = this.data.goodNum;
		if(this.data.goodList[0].skuList[this.data.currentNav].stock>this.data.goodNum){
			this.data.goodNum++;
			this.setData({
				goodNum: this.data.goodNum
			})
		}else{
			wx.showToast({
				title: '库存不足',
				icon: 'none'
			})
			return false
		}
		
		
	},
	// 点评
	handleComment() {
		var source = {
			id: this.data.id,
			page: this.data.searchGood.page,
			size: this.data.searchGood.size,
		}
		api.post(getCommentList.list, source).then(res => {
			console.log(res,1111)
			if (res.rows.length > 0) {
				for (var i = 0; i < res.rows.length; i++) {
					var pList = res.rows[i].commentPhoto
					if(res.rows[i].commentPhoto!=null){
						var photoList = (res.rows[i].commentPhoto.split(','))
						res.rows[i]['photoList'] = photoList
					}	
				}
				this.setData({
					commentList: res.rows,
					createTime: getTimeLeft(res.rows[0].createTime)
				})
			}
			// console.log(this.data.commentList)
		}).catch(err => {
			// console.log(err)
			wx.showToast({
				title: err.message,
				icon: 'none'
			})
		})
	},
	//与客服聊天
	serviceChat() {},
	// 加入购物车
	addToCar() {
		this.setData({
			specificationsWrap: false
		})
	},
	cancel() {
		this.setData({
			specificationsWrap: true
		})
		// var that=this;
		// var animation = wx.createAnimation({
		//   duration: 400,//动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
		//   timingFunction: 'ease',//动画的效果 默认值是linear
		// })
		// this.animation = animation
		// that.fadeDown();//调用隐藏动画   
		// setTimeout(function(){
		//   that.setData({
		//     specificationsWrap: true
		//   })      
		// },200)//先执行下滑动画，再隐藏模块
	},
	// 积分说明
	toMore() {
		wx.navigateTo({
			url: '../integralMore/integralMore?type=integral'
		})
	},
	onPullDownRefresh: function() {
		wx.showNavigationBarLoading() //在标题栏中显示加载
		this.setData({
			goodList:[]
		})
		this.getGoodList();
		// this.handleComment();
		setTimeout(function() {
			wx.hideNavigationBarLoading() //完成停止加载
			wx.stopPullDownRefresh() //停止下拉刷新
		}, 1500);
	},
	// handleShare(){
	// 	if(wx.getStorageSync('userInfo')==''){
	// 		
	// 		wx.showToast({
	// 			title: '暂未登录，请前去登录',
	// 			icon: 'none',
	// 			duration: 2000
	// 		})
	// 	}
	// }

})
